<template>
  <div>
    <!-- 主内容区域 -->
    <div class="main-content">
      <div class="page-title">关键词对比</div>

      <!-- 关键词对比 -->
      <div class="keyword-comparison">
        <div class="comparison-header">
          <div class="comparison-title">关键词对比分析</div>
          <el-button type="text" size="small" @click="clearAllKeywords">清空</el-button>
        </div>

        <div class="keyword-inputs">
          <div class="keyword-input" v-for="(keyword, index) in keywords" :key="index">
            <input
              type="text"
              placeholder="输入关键词"
              v-model="keywords[index]"
              @focus="showSuggestions(index)"
              @blur="hideSuggestionsDelayed(index)"
            >
            <i class="fa-solid fa-times-circle remove-keyword" @click="removeKeyword(index)" v-if="keywords.length > 1"></i>

            <!-- 关键词建议下拉框 -->
            <div v-if="showSuggestionBox[index]" class="suggestion-box">
              <div class="suggestion-item" v-for="(suggestion, sIndex) in getSuggestions(keywords[index])" :key="sIndex" @click="selectSuggestion(index, suggestion)">
                {{ suggestion }}
              </div>
            </div>
          </div>
        </div>

        <div class="add-keyword">
          <el-button type="text" size="small" @click="addKeyword">
            <i class="fa-solid fa-plus-circle"></i> 添加关键词
          </el-button>
        </div>

        <div class="compare-options">
          <div class="time-range">
            <span>时间范围：</span>
            <el-radio-group v-model="timeRange">
              <el-radio-button label="7d">近7天</el-radio-button>
              <el-radio-button label="30d">近30天</el-radio-button>
              <el-radio-button label="90d">近90天</el-radio-button>
              <el-radio-button label="180d">近180天</el-radio-button>
            </el-radio-group>
          </div>

          <div class="data-type">
            <span>数据类型：</span>
            <el-radio-group v-model="dataType">
              <el-radio-button label="views">搜索量</el-radio-button>
              <el-radio-button label="interaction">互动量</el-radio-button>
              <el-radio-button label="growth">增长率</el-radio-button>
            </el-radio-group>
          </div>

          <div class="compare-button">
            <el-button type="primary" @click="compareKeywords">开始对比</el-button>
          </div>
        </div>
      </div>

      <!-- 对比结果图表 -->
      <div v-if="showResults" class="comparison-charts">
        <!-- 趋势图 -->
        <div class="chart-card">
          <div class="chart-title">关键词趋势对比</div>
          <div class="chart-container">
            <canvas ref="trendChart"></canvas>
          </div>
        </div>

        <!-- 竞争度对比 -->
        <div class="chart-card">
          <div class="chart-title">竞争度对比</div>
          <div class="chart-container">
            <canvas ref="competitionChart"></canvas>
          </div>
        </div>

        <!-- 受众匹配度 -->
        <div class="chart-card">
          <div class="chart-title">受众匹配度</div>
          <div class="chart-container">
            <canvas ref="audienceChart"></canvas>
          </div>
        </div>
      </div>

      <!-- 对比数据表格 -->
      <div v-if="showResults" class="comparison-table">
        <div class="table-header">
          <div class="table-title">关键词数据对比</div>
          <el-button type="text" size="small" class="export-button" @click="exportData">
            <i class="fa-solid fa-download"></i> 导出数据
          </el-button>
        </div>

        <el-table :data="comparisonData" stripe style="width: 100%">
          <el-table-column prop="keyword" label="关键词"></el-table-column>
          <el-table-column prop="searchVolume" label="搜索量" :formatter="formatNumber"></el-table-column>
          <el-table-column prop="growthRate" label="增长率" :formatter="formatPercentage"></el-table-column>
          <el-table-column prop="competition" label="竞争度"></el-table-column>
          <el-table-column prop="interactionRate" label="互动率" :formatter="formatPercentage"></el-table-column>
          <el-table-column prop="audienceMatch" label="受众匹配度" :formatter="formatPercentage"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="mini" type="text" @click="analyzeSingleKeyword(scope.row.keyword)">详细分析</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 关键词建议 -->
      <div v-if="showResults" class="keyword-suggestions">
        <div class="suggestion-title">相关关键词建议</div>
        <div class="suggestion-tags">
          <div class="suggestion-tag" v-for="tag in relatedKeywords" :key="tag" @click="addRelatedKeyword(tag)">
            {{ tag }}
          </div>
        </div>
      </div>
    </div>

    <!-- 单个关键词分析弹窗 -->
    <el-dialog v-model="singleAnalysisVisible" title="关键词详细分析">
      <div class="single-analysis-content">
        <div class="keyword-detail">
          <div class="detail-header">
            <div class="keyword-name">{{ currentSingleKeyword }}</div>
            <div class="keyword-score">综合评分：<span class="text-primary">{{ keywordScore }}</span></div>
          </div>

          <div class="detail-stats">
            <div class="stat-item">
              <div class="stat-value">{{ formatNumber(singleKeywordData.searchVolume) }}</div>
              <div class="stat-label">搜索量</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ formatPercentage(singleKeywordData.growthRate) }}</div>
              <div class="stat-label">增长率</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ singleKeywordData.competition }}</div>
              <div class="stat-label">竞争度</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ formatPercentage(singleKeywordData.interactionRate) }}</div>
              <div class="stat-label">互动率</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ formatPercentage(singleKeywordData.audienceMatch) }}</div>
              <div class="stat-label">受众匹配度</div>
            </div>
          </div>

          <div class="detail-charts">
            <div class="chart-item">
              <div class="chart-title">搜索趋势</div>
              <div class="chart-container">
                <canvas ref="singleTrendChart"></canvas>
              </div>
            </div>

            <div class="chart-item">
              <div class="chart-title">受众画像</div>
              <div class="chart-container">
                <canvas ref="audienceProfileChart"></canvas>
              </div>
            </div>
          </div>

          <div class="detail-suggestions">
            <div class="suggestion-title">内容建议</div>
            <div class="suggestion-list">
              <div class="suggestion-item" v-for="(suggestion, index) in contentSuggestions" :key="index">
                <div class="suggestion-index">{{ index + 1 }}.</div>
                <div class="suggestion-text">{{ suggestion }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="singleAnalysisVisible = false">关闭</el-button>
          <el-button type="primary" @click="useThisKeyword">使用此关键词</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Chart from 'chart.js/auto';

export default {
  name: 'KeywordCompare-view',
  data() {
    return {
      activeMenu: 'keywords-compare',
      keywords: ['夏季穿搭', '显瘦搭配'],
      timeRange: '30d',
      dataType: 'views',
      showResults: false,
      comparisonData: [],
      relatedKeywords: [],
      showSuggestionBox: [false, false],
      suggestionList: [
        '夏季连衣裙', '显瘦上衣', '夏季短裤', '显高搭配', '夏季防晒',
        '秋季穿搭', '冬季穿搭', '春季穿搭', '日常穿搭', '通勤穿搭'
      ],
      singleAnalysisVisible: false,
      currentSingleKeyword: '',
      singleKeywordData: {},
      keywordScore: 0,
      contentSuggestions: [],
      // 图表实例存储
      trendChart: null,
      competitionChart: null,
      audienceChart: null,
      singleTrendChart: null,
      audienceProfileChart: null
    };
  },
  methods: {
    handleOpen() {
      // 处理侧边栏菜单展开事件
    },
    handleClose() {
      // 处理侧边栏菜单关闭事件
    },
    clearAllKeywords() {
      this.keywords = [];
    },
    showSuggestions(index) {
      this.showSuggestionBox[index] = true;
    },
    hideSuggestionsDelayed(index) {
      setTimeout(() => {
        this.showSuggestionBox[index] = false;
      }, 200);
    },
    getSuggestions(keyword) {
      if (!keyword) return [];
      return this.suggestionList.filter(item => item.includes(keyword));
    },
    selectSuggestion(index, suggestion) {
      this.keywords[index] = suggestion;
      this.showSuggestionBox[index] = false;
    },
    addKeyword() {
      this.keywords.push('');
      this.showSuggestionBox.push(false);
    },
    removeKeyword(index) {
      this.keywords.splice(index, 1);
      this.showSuggestionBox.splice(index, 1);
    },
    compareKeywords() {
      // 实现对比逻辑
      this.showResults = true;
      // 示例数据
      this.comparisonData = [
        {
          keyword: '夏季穿搭',
          searchVolume: 12000,
          growthRate: 0.15,
          competition: '中',
          interactionRate: 0.2,
          audienceMatch: 0.8
        },
        {
          keyword: '显瘦搭配',
          searchVolume: 10000,
          growthRate: 0.12,
          competition: '高',
          interactionRate: 0.18,
          audienceMatch: 0.75
        }
      ];
      this.relatedKeywords = ['夏季短裙', '显瘦长裤', '夏季凉鞋'];
      this.renderCharts();
    },
    renderCharts() {
      // 销毁旧的图表实例
      if (this.trendChart) this.trendChart.destroy();
      if (this.competitionChart) this.competitionChart.destroy();
      if (this.audienceChart) this.audienceChart.destroy();

      // 趋势图
      this.trendChart = new Chart(this.$refs.trendChart, {
        type: 'line',
        data: {
          labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          datasets: [
            {
              label: '夏季穿搭',
              data: [1200, 1300, 1400, 1500, 1600, 1700, 1800],
              borderColor: 'rgb(254, 44, 85)',
              tension: 0.1
            },
            {
              label: '显瘦搭配',
              data: [1000, 1100, 1200, 1300, 1400, 1500, 1600],
              borderColor: 'rgb(51, 153, 255)',
              tension: 0.1
            }
          ]
        },
        options: {
          responsive: true,
          plugins: {
            legend: {
              position: 'top'
            },
            title: {
              display: false
            }
          }
        }
      });

      // 竞争度对比
      this.competitionChart = new Chart(this.$refs.competitionChart, {
        type: 'bar',
        data: {
          labels: ['夏季穿搭', '显瘦搭配'],
          datasets: [
            {
              label: '竞争度',
              data: [3, 4],
              backgroundColor: ['rgba(254, 44, 85, 0.8)', 'rgba(51, 153, 255, 0.8)']
            }
          ]
        },
        options: {
          responsive: true,
          plugins: {
            legend: {
              position: 'top'
            },
            title: {
              display: false
            }
          }
        }
      });

      // 受众匹配度
      this.audienceChart = new Chart(this.$refs.audienceChart, {
        type: 'pie',
        data: {
          labels: ['夏季穿搭', '显瘦搭配'],
          datasets: [
            {
              label: '受众匹配度',
              data: [80, 75],
              backgroundColor: ['rgba(254, 44, 85, 0.8)', 'rgba(51, 153, 255, 0.8)']
            }
          ]
        },
        options: {
          responsive: true,
          plugins: {
            legend: {
              position: 'top'
            },
            title: {
              display: false
            }
          }
        }
      });
    },
    formatNumber(value) {
      // 检查 value 是否为 undefined 或 null
      if (value === undefined || value === null) {
        return '0'; // 或者返回空字符串 ''
      }
      return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    },
    formatPercentage(value) {
      return (value * 100).toFixed(1) + '%';
    },
    exportData() {
      // 实现导出数据逻辑
      console.log('导出数据');
    },
    analyzeSingleKeyword(keyword) {
      this.currentSingleKeyword = keyword;
      this.singleKeywordData = {
        searchVolume: 12000,
        growthRate: 0.15,
        competition: '中',
        interactionRate: 0.2,
        audienceMatch: 0.8
      };
      this.keywordScore = 85;
      this.contentSuggestions = [
        '使用夏季流行元素，如碎花、蕾丝等',
        '强调显瘦效果，搭配修身版型的衣物',
        '结合不同场景，提供多样化的穿搭方案'
      ];
      this.singleAnalysisVisible = true;
      this.renderSingleCharts();
    },
    renderSingleCharts() {
      // 销毁旧的图表实例
      if (this.singleTrendChart) this.singleTrendChart.destroy();
      if (this.audienceProfileChart) this.audienceProfileChart.destroy();

      // 搜索趋势
      this.singleTrendChart = new Chart(this.$refs.singleTrendChart, {
        type: 'line',
        data: {
          labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          datasets: [
            {
              label: '搜索量',
              data: [1200, 1300, 1400, 1500, 1600, 1700, 1800],
              borderColor: 'rgb(254, 44, 85)',
              tension: 0.1
            }
          ]
        },
        options: {
          responsive: true,
          plugins: {
            legend: {
              position: 'top'
            },
            title: {
              display: false
            }
          }
        }
      });

      // 受众画像
      this.audienceProfileChart = new Chart(this.$refs.audienceProfileChart, {
        type: 'pie',
        data: {
          labels: ['女性', '男性', '青年', '中年'],
          datasets: [
            {
              label: '受众比例',
              data: [60, 40, 70, 30],
              backgroundColor: [
                'rgba(254, 44, 85, 0.8)',
                'rgba(51, 153, 255, 0.8)',
                'rgba(76, 217, 100, 0.8)',
                'rgba(255, 149, 0, 0.8)'
              ]
            }
          ]
        },
        options: {
          responsive: true,
          plugins: {
            legend: {
              position: 'top'
            },
            title: {
              display: false
            }
          }
        }
      });
    },
    useThisKeyword() {
      // 实现使用此关键词逻辑
      console.log('使用关键词:', this.currentSingleKeyword);
      this.singleAnalysisVisible = false;
    }
  },
  mounted() {
    // 组件挂载时的逻辑
  }
};
</script>

<style scoped lang="scss">

/* 主内容区域 */
.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

/* 关键词对比相关样式 */
.keyword-comparison {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.comparison-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.comparison-title {
  font-size: 18px;
  font-weight: 500;
}

.keyword-inputs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.keyword-input {
  flex: 1;
  position: relative;
}

.keyword-input input {
  width: 100%;
  padding: 8px 16px;
  border-radius: 8px;
  border: 1px solid #EBEEF5;
  outline: none;
}

.keyword-input input:focus {
  border-color: var(--primary-color);
}

.remove-keyword {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--gray-color);
  cursor: pointer;
}

.add-keyword {
  margin-top: 10px;
}

.compare-options {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.time-range {
  display: flex;
  align-items: center;
  gap: 10px;
}

.compare-button {
  margin-left: auto;
}

/* 对比结果图表 */
.comparison-charts {
  display: grid;
  grid-template-columns: 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.chart-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}

.chart-container {
  height: 300px;
}

/* 对比数据表格 */
.comparison-table {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.export-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 关键词建议 */
.keyword-suggestions {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.suggestion-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}

.suggestion-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.suggestion-tag {
  padding: 8px 16px;
  background-color: #F8F8F8;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.suggestion-tag:hover {
  background-color: rgba(254, 44, 85, 0.1);
  color: var(--primary-color);
}


/* 单个关键词分析弹窗 */
.single-analysis-content {
  padding: 20px;
}

.keyword-detail {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.keyword-name {
  font-size: 18px;
  font-weight: 500;
}

.keyword-score {
  color: var(--primary-color);
  font-weight: 500;
}

.detail-stats {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 5px;
}

.stat-label {
  color: var(--gray-color);
  font-size: 14px;
}

.detail-charts {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-item {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.chart-item .chart-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}

.detail-suggestions {
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.suggestion-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.suggestion-item {
  display: flex;
  gap: 10px;
}

.suggestion-index {
  font-weight: 500;
}

.suggestion-text {
  flex: 1;
}
</style>
